const Router = require("koa-router");
const Service = require("../src/websocket/websocketService");

const router = new Router();
let ctxs = [];
router.all("/ws", (ctx) => {
  let id = ctx.query.id;
  // 管理员放在数组前面
  if (id === "admin") {
    ctxs.unshift(ctx.websocket);
  } else {
    ctxs.push(ctx.websocket);
  } 
  let service = new Service(ctx.websocket, ctxs);
  ctx.websocket.on("message", (message) => {
    console.info("请求参数", message);
    try {
      let params = JSON.parse(message);
      // 接口名称
      let { insName } = params;
      service[insName](params);
    } catch (error) {
      console.error("失败", error);
      ctx.websocket.send(
        JSON.stringify({
          query: message,
          insName: message.insName,
          code: 500,
          msg: error.message,
        })
      );
    }
  });
});

module.exports = router;